﻿using DeZhen.DataCollection.IRepository;
using SqlSugar;
using System.Linq.Expressions;

namespace DeZhen.DataCollection.Repository
{
    public class BaseRepository<TEntity> : SimpleClient<TEntity>, IBaseRepository<TEntity> where TEntity : class, new()
    {
        private readonly ISqlSugarClient _db;
        public BaseRepository(ISqlSugarClient db) : base(db)
        {
            _db = db;
        }


        public Task<TEntity> GetByIdAsync(long id)
        {
            return base.GetByIdAsync(id);
        }

        //public override async Task<List<TEntity>> GetListAsync()
        //{
        //    return await base.GetListAsync();
        //}
        public async Task<List<TEntity>> GetPagedListAsync(Expression<Func<TEntity, bool>> predicate, int page, int pageSize)
        {
            return await _db.Queryable<TEntity>()
                .Where(predicate)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
        }

        public async Task<bool> CreateAsync(TEntity entity)
        {
            return await base.InsertAsync(entity);
        }

        public async Task<long> CreateReturnIDAsync(TEntity entity)
        {
            return await base.InsertReturnBigIdentityAsync(entity);
        }

        public async Task<bool> CreateManyAsync(List<TEntity> entityList)
        {
            if (entityList == null || entityList.Count == 0)
                return false;
            var result = await _db.Insertable(entityList).ExecuteCommandAsync();
            return result > 0;
        }

        public async Task DeleteAsync(long id)
        {
            await base.DeleteByIdAsync(id);
        }

        public async Task<bool> DeleteManyAsync(List<TEntity> entityList)
        {
            if (entityList == null || entityList.Count == 0)
                return false;
            var result = await _db.Deleteable(entityList).ExecuteCommandAsync();
            return result > 0;
        }
    }
}
